Spring Framework:4.3.14.RELEASE
本文主要是论述 Spring Framework IOC 容器中 Bean 的命名。
- 每个 Bean 在 IOC 容器内都需要有身份标识
- 每个 Bean 可以拥有一个或多个身份标识
- 任意一个身份标识需要在 IOC 容器内唯一
基于 XML 方式的元数据配置方式中:
- Bean 的身份标识通过 id 或 name 属性标识。
- id 只能声明一个身份标识
- name 可以声明一个或一个以上的身份标识,多个身份标识之间通过逗号、分号、空格进行分隔
id 命名 Bean:
1 | <bean id="helloWorld" class="com.example.spring.HelloWorld"> |
name 命名 Bean:
1 | <bean name="helloWorld" class="com.example.spring.HelloWorld"> |
1 | <bean name="helloWorld,helloWorld1" class="com.example.spring.HelloWorld"> |
1 | <bean name="helloWorld;helloWorld1" class="com.example.spring.HelloWorld"> |
1 | <bean name="helloWorld helloWorld1" class="com.example.spring.HelloWorld"> |
id 和 name 一起命名 Bean:
1 | <bean id="helloWorld" name="helloWorld2,helloWorld3" class="com.example.spring.HelloWorld"> |
Bean 默认命名:
id 和 name 属性并不是必须的,若未进行声明,Spring Framework 将使用默认策略对 Bean 进行命名。
默认使用 类名的首字母小写名称作为 Bean 的身份标识。
但是推荐进行命名。
Bean 别名:
当 Bean 拥有多个身份标识时,他们等同于互为别名。但 Spring Framework 支持通过别名标签为 Bean 设置别名。
1 | <bean id="helloWorld" class="com.example.spring.HelloWorld"> |
1 | <bean name="helloWorld" class="com.example.spring.HelloWorld"> |
1 | <bean id="helloWorld" name="helloWorld1" class="com.example.spring.HelloWorld"> |
1 | <bean id="helloWorld" name="helloWorld1" class="com.example.spring.HelloWorld"> |
- alias 标签中 name 属性需是 Bean 的 id 或 name 属性值
- alias 标签中 alias 属性是别名值
- alias 标签可以对同一个 Bean 进行不同的别名设置
- alias 标签可以嵌套循环进行别名设置
- alias 标签的 alias 属性不能设置多个值
特别的别名设置:
1 | <bean id="helloWorld" class="com.example.spring.HelloWorld"> |
代码请参考example-02:
lxmuse-spring-example-02